import { queryFileByMD5Dao, uploadDao, queryFilesByConditonDao } from '../dao/loadDao';
import { UploadError } from '../utils/errors';

export const uploadService = async (data) => {
  // 校验参数
  if (!data) {
    throw new UploadError('上传失败, 请选择1个文件上传')
  }
  let targetFile = data['file']
  if (Array.isArray(targetFile)) {
    throw new UploadError('上传失败, 仅支持单个文件上传')
  } 
  if (targetFile.size > 1024 * 2000) {
    throw new UploadError('上传失败, 仅支持小于2MB的文件上传')
  }
  // 验证文件是否存在
  const file = await queryFileByMD5Dao(targetFile.md5)
  if (file.length > 0) {
    return file[0]
    // throw new UploadError(`上传的文件已存在，资源为 ${file[0].md5} 。`)
  }
  await uploadDao(targetFile)
  // 查询上传的文件
  const fileUploaded = await queryFileByMD5Dao(targetFile.md5)
  return fileUploaded[0]
}

export const queryFilesByConditonService = async (condition) => {
  return await queryFilesByConditonDao(condition)
}